package com.atguigu.gulimail.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimail.ware.dao.PurchaseDetailDao;
import com.atguigu.gulimail.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimail.ware.service.PurchaseDetailService;
import com.atguigu.gulimail.ware.service.WareSkuService;
import com.atguigu.gulimail.ware.vo.MergeVo;
import com.atguigu.gulimail.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimail.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimail.ware.dao.PurchaseDao;
import com.atguigu.gulimail.ware.entity.PurchaseEntity;
import com.atguigu.gulimail.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    PurchaseDetailDao detailDao;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 如果采购单状态 status =0 或者等于1.那就表示未领取
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryUnreceiveList(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    /**
     * 订单合并
     *
     * @param mergeVo
     */
    @Transactional
    @Override
    public void merge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        //创建完成/或者部位空。 合并订单。
        //合并的逻辑是  改变 wms_purchase_detail 里的 purchase_id  和 status  前提是点击要合并的订单项是新创建或者已分配的。
        List<Long> items = mergeVo.getItems();

        List<PurchaseDetailEntity> collect = items.stream().map(m -> {
            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(m);
            return purchaseDetailEntity;
        }).filter(f -> {
            return (f.getStatus() == WareConstant.PurchaseDetailStatus.ASSIGNED.getCode()
                    || f.getStatus() == WareConstant.PurchaseDetailStatus.CREATED.getCode());
        }).collect(Collectors.toList());


        if (collect != null || collect.size() > 0) {
            //如果  没有选择采购单。  则创建一个新的采购单
            if (purchaseId == null) {
                PurchaseEntity purchaseEntity = new PurchaseEntity();
                purchaseEntity.setCreateTime(new Date());
                purchaseEntity.setUpdateTime(new Date());
                purchaseEntity.setStatus(WareConstant.PurchaseStatus.CREATED.getCode());

                this.save(purchaseEntity);
                purchaseId = purchaseEntity.getId();
            }
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> purchaseDetailEntities = collect.stream().map(item -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();

                purchaseDetailEntity.setId(item.getId());
                purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatus.ASSIGNED.getCode());

                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailEntities);
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseId);
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);
        }


//        List<PurchaseDetailEntity> detailEntityList = items.stream().map(item -> {
//            PurchaseDetailEntity purchaseDetailEntity=new PurchaseDetailEntity();
//
//            purchaseDetailEntity.setId(item);
//            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
//            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatus.ASSIGNED.getCode());
//
//            return purchaseDetailEntity;
//        }).collect(Collectors.toList());
//
//        purchaseDetailService.updateBatchById(detailEntityList);
        //修改 采购单update时间


    }

    /**
     * 领取采购单
     *
     * @param ids 采购单id
     */
    @Override
    public void receivePuchase(List<Long> ids) {
        //1、判断采购单状态是不是新建或者已分配的状态。
        List<PurchaseEntity> filterStatus = ids.stream().map(m -> {
            PurchaseEntity byId = this.getById(m);
            return byId;
        }).filter(f -> {
            if (f.getStatus() == WareConstant.PurchaseStatus.CREATED.getCode() ||
                    f.getStatus() == WareConstant.PurchaseStatus.ASSIGNED.getCode()) {
                return true;
            } else {
                return false;
            }
        }).collect(Collectors.toList());
        //2、改变采购单状态。
        List<PurchaseEntity> purchaseEntities = filterStatus.stream().map(m -> {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(m.getId());
            purchaseEntity.setStatus(WareConstant.PurchaseStatus.RECEIVED.getCode());
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);
            return purchaseEntity;
        }).collect(Collectors.toList());
        //3、改变采购项状态。
        purchaseEntities.forEach(item -> {
            Long id = item.getId();
            List<PurchaseDetailEntity> list = purchaseDetailService.listPurchaseDetailByPucchaseId(id);
            List<PurchaseDetailEntity> collect = list.stream().map(m -> {
                m.setStatus(WareConstant.PurchaseDetailStatus.BUYING.getCode());
                return m;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(collect);
        });


    }


    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        /**
         *  id: 123,//采购单id
         *    items: [{itemId:1,status:4,reason:""}]//完成/失败的需求详情

         */
        Long id = purchaseDoneVo.getId();


        boolean flag = true;   //默认采购完成
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntities = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            Long detailEntieyId = item.getItemId();
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatus.HASERROR.getCode()) {
                flag = false;
                purchaseDetailEntity.setId(detailEntieyId);
                purchaseDetailEntity.setStatus(item.getStatus());
            } else {
                purchaseDetailEntity.setId(detailEntieyId);
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatus.FINISHED.getCode());
                //3、如果采购完成。修改库存数量。
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(detailEntieyId);

                wareSkuService.updateWareNum(detailEntity.getSkuId(), detailEntity.getSkuNum(), detailEntity.getWareId());


            }
            purchaseDetailEntities.add(purchaseDetailEntity);
        }
        //2、修改采购单项状态
        purchaseDetailService.updateBatchById(purchaseDetailEntities);
        //1、修改采购单状态。 采购单的状态时根据采购项目来完成的。
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatus.FINISHED.getCode() : WareConstant.PurchaseStatus.HASERROR.getCode());

        this.updateById(purchaseEntity);


    }

}


